package com.codejie.pms.controller;

import com.codejie.pms.entity.Customer;
import com.codejie.pms.entity.Staff;
import com.codejie.pms.entity.StaffKpi;
import com.codejie.pms.service.CustomerService;
import com.codejie.pms.service.StaffKpiService;
import com.codejie.pms.service.StaffService;
import com.codejie.pms.util.DateUtil;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDate;
import java.util.*;

@Controller
public class StaffController {
    @Autowired
    private StaffService staffService;

    @Autowired
    private StaffKpiService staffKpiService;

    //去到显示员工信息界面
    @GetMapping("/staff_msg/{staffId}")
    public String getMsgPage(@PathVariable("staffId")String staffId, Model model){
        //this.customerId=id;
        Staff staff = staffService.getStaff(staffId);
        model.addAttribute("staff",staff);
        //return "admin/updateCustomer";
        return "admin/staff_msg";
        //return "admin/reviseCustomer";
    }

    //打开所有员工信息页面
    //model用于给前端返回数据
    @RequestMapping("/staffs")
    public String list(Model model) {
        Collection<Staff> staffs = staffService.selectStaffList();
        model.addAttribute("staffs", staffs);
        return "admin/all_staff";
    }

    //去到增加员工页面
    @GetMapping("/addStaff")
    public String toAddStaff(Model model){
        return "admin/addStaff";
    }

    //增加员工
    @PostMapping("/addStaff")
    public String addCustomer(Staff staff){
        if(staff.getStaffId()!=null)
            staffService.addStaff(staff);
        return "redirect:/staffs";    //返回emps请求 到展示所有员工信息页面
    }

    @RequestMapping("/cancelAddStaff")
    public String cancelAddStaff(){
        return "redirect:/staffs";
    }

    //去到修改员工信息页面
    @GetMapping("/reviseStaff/{staffId}")
    public String getUpdatePage(@PathVariable("staffId")String staffId,Model model){
        Staff staff = staffService.getStaff(staffId);
        model.addAttribute("staff",staff);
        return "admin/reviseStaff";
        //return "admin/customer_msg";
    }

    //修改员工
    @PostMapping("/reviseStaff")
    public String reviseMethod(Staff staff){
        staffService.updateStaff(staff);
        return "redirect:/staffs";
    }

    @GetMapping("/deleteStaff/{staffId}")
    public String deleteMethod(@PathVariable("staffId")String staffId,Model model){
        staffService.deleteStaff(staffId);
        return "redirect:/staffs";
    }

    //以execl导出员工列表
    @RequestMapping(value = "/staff/export")
    public void exportallDocumentaryExcel(HttpServletResponse response) throws IOException {
        try {
            List<Staff> staffList = staffService.selectStaffList();
            // 在内存中创建一个Excel文件，通过输出流写到员工端提供下载
            // 内存中保留 10000 条数据，以免内存溢出，其余写入 硬盘
            SXSSFWorkbook workbook = new SXSSFWorkbook(10000);
            CellStyle style = workbook.createCellStyle();
            style.setAlignment(XSSFCellStyle.ALIGN_CENTER);//SXSSFWorkbook方式的居中
            // 创建一个sheet页
            SXSSFSheet sheet = (SXSSFSheet) workbook.createSheet("表格");
            // 分别设置Excel列的宽度

            for(int i=0;i<10;i++){
                sheet.setColumnWidth(i, 4000);
            }
            // 创建标题
            SXSSFRow headRow = (SXSSFRow) sheet.createRow(0);
            headRow.createCell(0).setCellValue("员工号");
            headRow.createCell(1).setCellValue("姓名");
            headRow.createCell(2).setCellValue("电话");
            headRow.createCell(3).setCellValue("邮箱");
            headRow.createCell(4).setCellValue("上级主管");
            headRow.createCell(5).setCellValue("性别");
            headRow.createCell(6).setCellValue("kpi");
            headRow.createCell(7).setCellValue("工资");
            headRow.createCell(8).setCellValue("评价");

            for (Staff staff : staffList) {
                // 创建行
                SXSSFRow dataRow = (SXSSFRow) sheet.createRow(sheet.getLastRowNum() + 1);

                dataRow.createCell(0).setCellValue(staff.getStaffId());
                dataRow.createCell(1).setCellValue(staff.getStaffName());
                dataRow.createCell(2).setCellValue(staff.getPhone());
                dataRow.createCell(3).setCellValue(staff.getEmail());
                dataRow.createCell(4).setCellValue(staff.getModelManager());
                dataRow.createCell(5).setCellValue(staff.getGender()==0?"女":"男");
                dataRow.createCell(6).setCellValue(staff.getKpi());
                dataRow.createCell(7).setCellValue(staff.getWages());
                dataRow.createCell(8).setCellValue(staff.getEvaluate());
            }

            // 设置Excel文件名，并以中文进行编码
            String codedFileName = new String("员工列表".getBytes("gbk"), "iso-8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="
                    + codedFileName + DateUtil.getCurrentTime2()
                    +".xlsx");
            // 响应类型,编码
            response.setContentType("application/octet-stream;charset=UTF-8");
            // 形成输出流
            OutputStream osOut = response.getOutputStream();
            // 将指定的字节写入此输出流
            workbook.write(osOut);
            // 刷新此输出流并强制将所有缓冲的输出字节被写出
            osOut.flush();
            // 关闭流
            osOut.close();
            /*
             * dispose of temporary files backing this workbook on disk
             * 处理在磁盘上备份此工作簿的临时文件 SXSSF分配临时文件，必须始终清除显式，通过调用dispose方法
             */
            workbook.dispose();

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println( "导出员工失败！失败信息："+e.getMessage());
        }
    }

    //去到员工绩效页面
    @GetMapping("/staff_kpi/{staffId}")
    public String toStaffKpi(@PathVariable("staffId")String staffId,Model model){
        List<StaffKpi> staffKpiList = staffKpiService.getStaffKpiList(staffId);
        model.addAttribute("staffKpis",staffKpiList);
        //System.out.println(staffId);
        return "/admin/staff_kpi";
    }

    /*
        kpi和工资计算方式:
        kpi=上个月完成或正在进行的项目的DPA总和
        工资=固定工资3000+kpi*1500-缺勤数*50
    */
    @GetMapping("/calculateWages")
    public String calculateWages(Model model){
        //获取所有员工
        List<Staff> staffList = staffService.selectStaffList();
        //获取所有员工kpi
        List<StaffKpi> staffKpiList = staffKpiService.getAllStaffKpiList();

        String staffId;
        double kpi=0;
        double wages=0;
        int absence=0;
        //遍历每个员工 计算每个员工的kpi和工资
        for (Staff staff: staffList) {
            staffId = staff.getStaffId();
            //遍历staffKpi 找到员工所属项目
            for (StaffKpi staffKpi : staffKpiList){
                //如果对应员工id 且项目完成时间是上一个月或正在进行
                if(staffId.equals(staffKpi.getStaffId())
                        &&(staffKpi.getProEndDate()==null
                        || DateUtil.daysOfTwo(DateUtil.localDateToDate(LocalDate.now()),staffKpi.getProEndDate())<=31)){
                    //计算员工kpi
                    System.out.println("2333");
                    System.out.println(staffId);
                    if(staffKpi.getCompletion().equals("优"))
                        kpi+=staffKpi.getGPA();
                    if(staffKpi.getCompletion().equals("良"))
                        kpi+=staffKpi.getGPA()*0.8;
                    if(staffKpi.getCompletion().equals("差"))
                        kpi+=staffKpi.getGPA()*0.5;
                    absence = staffKpi.getAbsence();
                }
            }
            //员工工资等于固定工资3000+kpi*1500-缺勤数*50
            wages=3000+kpi*1500-absence*50;
            //重设员工的kpi和工资
            staff.setKpi(kpi);
            staff.setWages(wages);
            staffService.calculateKpiWages(staff);
            absence=0;
            kpi=0;
            wages=0;
        }
        return "redirect:/staffs";
    }

    @PostMapping("/searchStaff")
    public String searchStaffMethod(String staffId,Model model){
        Staff staff = staffService.getStaff(staffId);
        model.addAttribute("staffs",staff);
        //System.out.printf(staffId);
        return "admin/all_staff";
    }

    //转到员工工作情况页面
    @GetMapping("/staffWorkSituation")
    public String toStaffWorkSituation(Model model){
        int x=1,y=5; //kpi最小和最大值
        List randKpi=new ArrayList();
        //产生kpi随机数
        Random random = new Random();
        for (int i=0;i<12;i++){
            //int a=random.nextInt(5)+1;
            double a=x + Math.random() * y % (y - x + 1);
            String str = String.format("%.2f", a);
            randKpi.add(Double.valueOf(str));
        }

        //randKpi[1]=random.nextInt(5+1);
        model.addAttribute("kpis",randKpi);
        return "admin/staffWorkSituation";
    }

//    @RequestMapping("/staffWorkSituation")
//    public String toStaffWorkSituation(){
//        return "admin/staffWorkSituation";
//    }

    //展示员工绩效
//    @RequestMapping("/staffKpis")
//    public String showAllStaffKpiList(Model model){
//        System.out.println("123456");
//        System.out.println(this.theSearchStaffID);
//        List<StaffKpi> staffKpiList = staffKpiService.getStaffKpiList(theSearchStaffID);
//        model.addAttribute("staffKpis",staffKpiList);
//        return "admin/staff_kpi";
//    }
}
